package com.mishow.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.adapter.MyReleaseAdapter;
import com.mishow.bean.Announcement;
import com.mishow.fragment.base.BaseFragment;
import com.mishow.log.MyLog;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.refresh.PullPushRefreshLayout;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.AnnouncementResponse;
import com.mishow.request.response.AnnouncementResponse.Result;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.EmptyDataLayout;
import com.mishow.widget.MyListView;
/**
 * 
 * 作者：wei.miao <br/>
 * 描述：我的发布Fragment
 */
public class MyReleaseFragment extends BaseFragment implements OnRefreshListener, PullPushRefreshLayout.OnLoadListener{
	
	
	private Context mContext;
	/** 全部 **/
	public static final int STATUS_ALL = 0;
	/** 招募中 **/
	public static final int STATUS_RECRUIT = 1; 
	/** 已过期 **/
	public static final int STATUS_PAST= 2; 
	/** 已关闭 **/
	public static final int STATUS_CLOSE = 3;
	
	private int pageNo = 1;
	
	private int pageSize = 10;
	
	
	/** 列表总条数 **/
	private int total;
	/** 是否正在网络请求中默认为false **/
	private boolean isReflesh;
	/** 刷新操作 **/
	public static final int ACTION_REFRESH = 1;
	/** 加载更多操作 **/
	public static final int ACTION_LOAD_MORE = 2;
	
	private MyReleaseAdapter myReleaseAdapter;
	
	private ArrayList<Announcement> mReleases;
	/** 发布状态  **/
	private int releaseStatus;
	/** 数据为空时的显示 **/
	private EmptyDataLayout empty_layout;
	/** 刷新加载框架 **/
	private PullPushRefreshLayout refresh_layout;
	/** 发布列表 **/
	private MyListView listview_release; 
	
	public static MyReleaseFragment newInstance() {
		
		MyReleaseFragment fragment = new MyReleaseFragment();
		return fragment;
	}
	
	public static MyReleaseFragment newInstance(int status) {
		MyLog.d("newInstance================");
		Bundle args = new Bundle();
		args.putInt("releaseStatus", status);
		MyReleaseFragment fragment = new MyReleaseFragment();
		fragment.setArguments(args);
		return fragment;
	}
	
	
	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		this.mContext = context;
	}
	
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		
		View view = inflater.inflate(R.layout.fragment_myrelease_list, null);
		initView(view);
		initData();
		setAttribute();
		return view;
	}
	/**
	 * 初始化界面
	 */
	private void initView(View v) {
		empty_layout = (EmptyDataLayout) v.findViewById(R.id.empty_layout);
		refresh_layout = (PullPushRefreshLayout) v.findViewById(R.id.refresh_layout);
		listview_release = (MyListView) v.findViewById(R.id.listview_release);
	}
	/**
	 * 初始化数据
	 */
	private void initData() {
		Bundle args = getArguments();
		if (args != null) {
			releaseStatus = args.getInt("releaseStatus");
		}
		mReleases = new ArrayList<>();
		myReleaseAdapter = new MyReleaseAdapter(mContext, mReleases,true);
	}
	
	private void setAttribute() {
		
		MyLog.d("setAttribute================");
		
		refresh_layout.setListView(listview_release);
		
		refresh_layout.setOnRefreshListener(this);
		refresh_layout.setOnLoadListener(this);

		
		listview_release.setAdapter(myReleaseAdapter);
		listview_release.setOnItemClickListener(onItemClickListener);
		
		onRefresh();
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			
			
		}
	};

	/**
	 * 加载更多
	 */
	@Override
	public void onLoad() {
		if (total > mReleases.size()) {
			pageNo++;
			getMyReleaseFromApi(ACTION_LOAD_MORE);
		} else {
			loadCompleted();
		}
	}

	/**
	 * 刷新
	 */
	@Override
	public void onRefresh() {
		MyLog.d("onRefresh================");
		pageNo = 1;
		getMyReleaseFromApi(ACTION_REFRESH);
	}
	/**
	 * 服务端获取我的发布列表
	 * @param action 区分刷新或加载更多
	 */
	private void getMyReleaseFromApi(final int action) {

		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		if(isReflesh){
			return ;
		}
		isReflesh = true;
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("pageNo", pageNo+"");
		params.put("pageSize", pageSize+"");

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.GET_QUERY_ANNOUNCEMENT_PAGE);
		OnResponseListener<AnnouncementResponse> listener = new OnResponseListener<AnnouncementResponse>(mContext) {

			@Override
			public void onSuccess(AnnouncementResponse response) {

				Result result = response.getBody().getResult();
				ArrayList<Announcement> dataList = result.getDataList();
				
				if (dataList != null && dataList.size() > 0) {
					total = response.getBody().getResult().getTotal();
					if (action == ACTION_REFRESH) {
						handlerRefresh(dataList);
					} else if (action == ACTION_LOAD_MORE) {
						handleLoadMore(dataList);
					}
				}
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
				if (action == ACTION_LOAD_MORE) {
					pageNo--;
				}
			}

			@Override
			public void onCompleted() {
				isReflesh = false;
				dismissProgress();
				loadCompleted();
			}
		};
		executeRequest(new FastJsonRequest<AnnouncementResponse>(
				Request.Method.POST, postUrl, AnnouncementResponse.class,
				listener, listener).setParams(lastParams));

	}
	
	/**
	 * 刷新后的数据
	 * @param results
	 */
	private void handlerRefresh(ArrayList<Announcement> results) {
		if (results == null || results.isEmpty()) {
			mReleases.clear();
			myReleaseAdapter.notifyDataSetChanged();
			empty_layout.setVisibility(View.VISIBLE);
		} else {
			empty_layout.setVisibility(View.GONE);
			mReleases.clear();
			mReleases.addAll(results);
			myReleaseAdapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 加载更多数据 
	 * @param results
	 */
	private void handleLoadMore(ArrayList<Announcement> results) {
		if (results != null && !results.isEmpty()) {
			mReleases.addAll(results);
			myReleaseAdapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 加载完成
	 */
	private void loadCompleted() {

		refresh_layout.setRefreshing(false);
		refresh_layout.setLoading(false);
		// 获取到全部数据后，则隐藏加载更多
		if (total > mReleases.size()) {
			refresh_layout.setCanLoadMore(true);
		} else {
			refresh_layout.setCanLoadMore(false);
		}
	}

}
